<template>
  <div class="crime-growth-chart">
    <div class="chart-header">
      <h3>罪犯增长率趋势</h3>
      <div class="trend-indicator">
        <span class="trend-value">{{ currentGrowthRate }}%</span>
        <span class="trend-label">当前增长率</span>
      </div>
    </div>
    <div class="chart-container" ref="chartContainer"></div>
  </div>
</template>

<script>
import { Chart } from '@antv/g2'

export default {
  name: 'CrimeGrowthChart',
  data() {
    return {
      chart: null,
      currentGrowthRate: 0,
      mockData: []
    }
  },
  mounted() {
    this.generateMockData()
    this.initChart()
    // this.startDataUpdate()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.destroy()
    }
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
    }
  },
  methods: {
    generateMockData() {
      const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      this.mockData = []

      // 基础增长率，从较低值开始，整体趋势向上
      let baseGrowth = 2.5

      months.forEach((month, index) => {
        // 模拟季节性波动和整体增长趋势
        const seasonalFactor = Math.sin((index / 12) * 2 * Math.PI) * 0.3  // 减少季节性波动
        const trendFactor = index * 0.4 // 增强整体向上趋势
        const randomFactor = (Math.random() - 0.5) * 0.8  // 减少随机波动

        const growthRate = baseGrowth + seasonalFactor + trendFactor + randomFactor
        const finalRate = Math.max(0.5, Math.round(growthRate * 10) / 10)

        this.mockData.push({
          month,
          growthRate: finalRate,
          date: `2024-${String(index + 1).padStart(2, '0')}`
        })

        if (index === months.length - 1) {
          this.currentGrowthRate = finalRate
        }
      })
    },

    initChart() {
      this.$nextTick(() => {
        try {
            if (this.chart) {
             this.chart.destroy()
            }

            const container = this.$refs.chartContainer
            if (!container) return

            this.chart = new Chart({
              container,
              autoFit: true,
              height: container.offsetHeight
            })

            this.chart.data(this.mockData)

            // 设置坐标轴
            this.chart.axis(false)

            // 主趋势线
            this.chart
              .line()
              .encode('x', 'month')
              .encode('y', 'growthRate')
              .style({
                stroke: '#00ffff',
                lineWidth: 3,
                shadowColor: '#00ffff',
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                lineJoin: 'round',
                lineCap: 'round'
              })
              .animate('enter', { type: 'pathIn', duration: 1000 })

            // 数据点
            this.chart
              .point()
              .encode('x', 'month')
              .encode('y', 'growthRate')
              .encode('size', 6)
              .style({
                stroke: '#ffffff',
                lineWidth: 2,
                shadowColor: '#00ffff',
                shadowBlur: 8,
                fill: '#00ffff'
              })
              .tooltip({
                title: 'month',
                items: [{
                  field: 'growthRate',
                  valueFormatter: (value) => `增长率: ${value}%`
                }]
              })

            // 填充区域
            this.chart
              .area()
              .encode('x', 'month')
              .encode('y', 'growthRate')
              .encode('color', '#00ffff')
              .style({
                fillOpacity: 0.3,
                shadowColor: '#00ffff',
                shadowBlur: 5
              })
              .animate('enter', { type: 'fadeIn', duration: 800 })

            // 趋势线标记（暂时移除，避免复杂性）
            // 趋势文字（暂时移除，避免复杂性）

            this.chart.theme({
            background: 'transparent',
            view: {
                viewFill: 'transparent'
            }
            })

            this.chart.render()
        } catch (error) {
            console.error('初始化图表失败:', error)
        }
        
      })
    },

    startDataUpdate() {
      this.updateTimer = setInterval(() => {
        this.updateChartData()
      }, 8000) // 每8秒更新一次
    },

    updateChartData() {
      // 更新最新一个月的数据
      const lastData = this.mockData[this.mockData.length - 1]
      const change = (Math.random() - 0.4) * 0.5 // 略微偏向增长
      lastData.growthRate = Math.max(0.5, Math.round((lastData.growthRate + change) * 10) / 10)
      this.currentGrowthRate = lastData.growthRate

      if (this.chart) {
        this.chart.changeData(this.mockData)
      }
    }
  }
}
</script>

<style scoped>
.crime-growth-chart {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: linear-gradient(145deg,
    rgba(0, 80, 120, 0.12) 0%,
    rgba(0, 100, 140, 0.08) 30%,
    rgba(0, 60, 100, 0.05) 70%,
    rgba(0, 90, 130, 0.08) 100%
  ),
  radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.08) 0%, transparent 50%),
  rgba(0, 0, 0, 0.5);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid rgba(0, 100, 150, 0.3);
  backdrop-filter: blur(10px);
  box-shadow:
    0 8px 32px rgba(0, 100, 150, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-shrink: 0;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(45deg,
    rgba(0, 120, 160, 0.9) 0%,
    rgba(0, 100, 140, 0.8) 50%,
    rgba(0, 80, 120, 0.7) 100%
  );
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 0 10px rgba(0, 100, 150, 0.4);
}

.trend-indicator {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.trend-value {
  font-size: 24px;
  font-weight: bold;
  color: #00ffff;
  text-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
}

.trend-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.chart-container {
  flex: 1;
  /* min-height: 250px; */
  border-radius: 8px;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .crime-growth-chart {
    padding: 15px;
  }

  .chart-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .chart-header h3 {
    font-size: 14px;
  }

  .trend-value {
    font-size: 20px;
  }

  .chart-container {
    min-height: 200px;
  }
}
</style>
